<template>
  <div class="login">
    <div class="login-form">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <h3>叩丁狼商品管理系统</h3>
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            prefix-icon="el-icon-user-solid"
            v-model="ruleForm.username"
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            v-model="ruleForm.password"
            autocomplete="off"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
 
<script>
import { loginApi } from '@/request/api'
import { UPDATE_USER_INFO } from '@/store/types'
import { dynamicRoutes } from '@/router'
export default {
  methods: {
    submit() {
      // 点击提交的时候，还要进行数据的验证
      // this.$refs.ruleForm.validate(valid=>{
      //   if(valid){
      //     // 成功的逻辑
      //   }else{
      //     // 失败的逻辑
      //   }
      // })

      this.$refs.ruleForm.validate().then(res => {
        // 成功的逻辑
        // 发请求
        loginApi({
          // password: this.ruleForm.password,
          // username: this.ruleForm.username
          ...this.ruleForm
        }).then(res => {
          const { token, tokenHead } = res.data
          localStorage.setItem('token', tokenHead + token)
          // 登录成功后，要再请求权限菜单
          this.$store.dispatch(UPDATE_USER_INFO).then(() => {
            // 先生成路由
            dynamicRoutes()
            // 要先生成路由，才能跳转到 index
            this.$router.push('/index')
          })

        }).catch(err => {
          console.log(err);
        })
      }).catch(err => {
        this.$message.error('请填写用户名和密码')
      })
    }
  },
  data() {
    return {
      ruleForm: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      }
    }
  }
}
</script>
 
<style lang = "less" scoped>
.login {
  background-color: #2d3a4b;
  height: 100%;
  .login-form {
    width: 400px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    h3 {
      font-size: 28px;
      color: #fff;
      text-align: center;
      line-height: 50px;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>